using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Study003_Swagger_Swashbuckle.Models;

namespace Study001_todo.Controllers
{
    /// <summary>
    /// Todo操作接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Produces("application/json")] // 声明控制器的操作支持 application/json 的响应内容类型
    public class TodoItemsController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoItemsController(TodoContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 查询所有结果
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            if (_context.TodoItems == null)
            {
                return NotFound();
            }
            return await _context.TodoItems.ToListAsync();
        }

        /// <summary>
        /// 按照id查询
        /// </summary>
        ///
        /// <param name="id">唯一值</param>
        /// <returns>查询集合</returns>
        /// <remarks>
        /// 返回示例：
        /// ```json
        ///     {
        ///     "id": 1,
        ///     "name": "叶",
        ///     "isComplete": true
        ///     }
        /// ```
        /// </remarks>
        /// <response code="400"> 如果查询不到结果 </response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<ActionResult<TodoItem>> GetTodoItem(long id)
        {
            if (_context.TodoItems == null)
            {
                return NotFound();
            }
            var todoItem = await _context.TodoItems.FindAsync(id);

            if (todoItem == null)
            {
                return NotFound();
            }

            return todoItem;
        }

        /// <summary>
        /// 修改记录
        /// </summary>
        /// <param name="id">唯一值</param>
        /// <param name="item">修改的实体</param>
        /// <returns></returns>
        /// <response code="204"> 修改成功 </response>
        /// <response code="400"> [id]与[item]中id不一致 </response>
        /// <response code="404"> 未找到[id]对应记录 </response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public async Task<IActionResult> PutTodoItem(long id, TodoItem item)
        {
            if (id != item.Id)
            {
                return BadRequest();
            }

            var todoItem = await _context.TodoItems.FindAsync(id);
            if (todoItem == null)
            {
                return NotFound();
            }

            todoItem.Name = item.Name;
            todoItem.IsComplete = item.IsComplete;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException) when (!TodoItemExists(id))
            {
                return NotFound();
            }

            return NoContent();
        }

        /// <summary>
        /// 新增记录
        /// </summary>
        /// <param name="todoItem">记录实体</param>
        /// <returns></returns>
        /// <response code="201"> 如果是新创建的对象 </response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
        {
            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();

            return CreatedAtAction(
                nameof(GetTodoItem),
                new { id = todoItem.Id },
                todoItem);
        }

        /// <summary>
        /// 删除记录
        /// </summary>
        /// <param name="id">唯一值</param>
        /// <returns></returns>
        /// <response code="204"> 删除成功 </response>
        /// <response code="404"> 未找到[id]对应记录 </response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeleteTodoItem(long id)
        {
            if (_context.TodoItems == null)
            {
                return NotFound();
            }
            var todoItem = await _context.TodoItems.FindAsync(id);
            if (todoItem == null)
            {
                return NotFound();
            }

            _context.TodoItems.Remove(todoItem);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool TodoItemExists(long id)
        {
            return (_context.TodoItems?.Any(e => e.Id == id)).GetValueOrDefault();
        }

    }
}
